import { Dimensions, View, StyleSheet } from "react-native";
import React, { useState } from "react";
import StandardHomeSearch from "@/components/standard-home/standard-home-search";
import { TabView, TabBar } from "react-native-tab-view";
import CompListView from "@/app/(tabs)/(standard-home)/comp-list-view";

// 获取屏幕宽度，用于 TabView 的布局
const initialLayout = { width: Dimensions.get("window").width };

const routes = [
  { key: "yi", title: "第1个" },
  { key: "er", title: "第二个" },
  { key: "san", title: "第3个" },
  { key: "si", title: "第4个" },
  { key: "wu", title: "第5个" },
  { key: "liu", title: "第6个" },
  { key: "qi", title: "第7个" },
];

// 这是一个统一的内容渲染组件，根据传入的索引显示不同内容
const ContentArea = ({ index }) => {
  // 模拟不同Tab的数据
  const data = [
    { title: "这是第一个页面的内容", backgroundColor: "white" },
    { title: "这是第二个页面的内容", backgroundColor: "lightblue" },
    { title: "这是第3个页面的内容", backgroundColor: "lightblue" },
    { title: "这是第4个页面的内容", backgroundColor: "lightblue" },
    { title: "这是第5个页面的内容", backgroundColor: "lightblue" },
    { title: "这是第6个页面的内容", backgroundColor: "lightblue" },
    { title: "这是第7个页面的内容", backgroundColor: "lightblue" },
  ];

  const currentData = data[index] || data[0]; // 如果索引超出范围，使用默认数据

  return (
    <View
      style={[
        styles.contentContainer,
        { backgroundColor: currentData.backgroundColor },
      ]}
    >
      <CompListView></CompListView>
    </View>
  );
};

const Index = () => {
  const [index, setIndex] = useState(0);

  const renderTabBar = (props: any) => (
    <TabBar
      {...props}
      scrollEnabled={true} // 启用水平滚动
      tabStyle={{ width: "auto" }} // 让 Tab 宽度自适应
      indicatorStyle={{ backgroundColor: "white" }}
      style={{ backgroundColor: "pink" }}
    />
  );

  const renderScene = ({ route }: { route: { key: string } }) => {
    // 根据当前激活的路由键找到索引
    const currentIndex = routes.findIndex((r) => r.key === route.key);
    // 渲染同一个组件，并传入索引作为 props
    return <ContentArea index={currentIndex} />;
  };

  return (
    <View style={{ flex: 1 }}>
      {/*首页搜索*/}
      <StandardHomeSearch></StandardHomeSearch>
      {/*tabs*/}
      <TabView
        navigationState={{ index, routes }}
        renderTabBar={renderTabBar}
        initialLayout={initialLayout}
        style={{ backgroundColor: "red" }}
        onIndexChange={setIndex}
        renderScene={renderScene} // 渲染的内容
      />
    </View>
  );
};

const styles = StyleSheet.create({
  scene: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
  sceneText: {
    color: "white",
    fontSize: 20,
    fontWeight: "bold",
  },
  contentContainer: {
    flex: 1,
  },
  contentText: {
    color: "black",
    fontSize: 20,
    fontWeight: "bold",
  },
});

export default Index;
